// 32feet.NET - Personal Area Networking for .NET
//
// InTheHand.Windows.Forms.SelectBluetoothDeviceDialogForm
// 
// Copyright (c) 2003-2008 In The Hand Ltd, All rights reserved.
// This source code is licensed under the In The Hand Community License - see License.txt



using System;
using System.Drawing;
using System.Collections;
using InTheHand.ComponentModel;
using System.Net.Sockets;
using System.Windows.Forms;
using InTheHand.Net.Sockets;
using InTheHand.Net.Bluetooth;

using System.Runtime.InteropServices;

namespace InTheHand.Windows.Forms
{
	/// <summary>
	/// Managed code dialog for Windows CE systems.
	/// </summary>
	internal class SelectBluetoothDeviceForm : System.Windows.Forms.Form
	{
        private const int LVS_EX_GRADIENT = 0x20000000;
        private const int LVM_SETEXTENDEDLISTVIEWSTYLE = 0x1036;
        //private const int GWL_EXSTYLE = -20;

        [DllImport("coredll")]
        private static extern int SendMessage(IntPtr hWnd, int Msg, int wParam, int lParam);

        //private static extern int SetWindowLong(IntPtr hWnd, int nIndex, int dwNewLong);

        //[DllImport("coredll")]
        //private static extern int GetWindowLong(IntPtr hWnd, int nIndex); 


		private System.Windows.Forms.MainMenu mainMenu1;
		private System.Windows.Forms.MenuItem mnuMenu;
		private System.Windows.Forms.MenuItem mnuSelect;
		private System.Windows.Forms.MenuItem mnuAgain;
		private System.Windows.Forms.ListView lvDevices;
		private System.Windows.Forms.MenuItem mnuCancel;

		private BluetoothDeviceInfo[] devices;
		public BluetoothDeviceInfo selectedDevice;
		private System.Windows.Forms.ColumnHeader clmDevice;
        internal bool fShowAuthenticated, fShowRemembered, fShowUnknown, fForceAuthentication;
        //private BLUETOOTH_SELECT_DEVICE_PARAMS selectDeviceParams;
		
		private BackgroundWorker bkSearch;
	
		public SelectBluetoothDeviceForm(/*BLUETOOTH_SELECT_DEVICE_PARAMS p*/)
		{
			//
			// Required for Windows Form Designer support
			//
			InitializeComponent();

			//
			// TODO: Add any constructor code after InitializeComponent call
			//
            //selectDeviceParams = p;

			bkSearch = new BackgroundWorker();
			bkSearch.DoWork+=new DoWorkEventHandler(bkSearch_DoWork);
			bkSearch.RunWorkerCompleted+=new RunWorkerCompletedEventHandler(bkSearch_RunWorkerCompleted);

            fShowAuthenticated = true;
            fShowRemembered = true;
            fShowUnknown = true;
            fForceAuthentication = false;

            
		}

		/// <summary>
		/// Clean up any resources being used.
		/// </summary>
		protected override void Dispose( bool disposing )
		{
			base.Dispose( disposing );
		}

		#region Windows Form Designer generated code
		/// <summary>
		/// Required method for Designer support - do not modify
		/// the contents of this method with the code editor.
		/// </summary>
		private void InitializeComponent()
		{
            System.Windows.Forms.ListViewItem listViewItem1 = new System.Windows.Forms.ListViewItem();
            this.lvDevices = new System.Windows.Forms.ListView();
            this.clmDevice = new System.Windows.Forms.ColumnHeader();
            this.mainMenu1 = new System.Windows.Forms.MainMenu();
            this.mnuSelect = new System.Windows.Forms.MenuItem();
            this.mnuMenu = new System.Windows.Forms.MenuItem();
            this.mnuAgain = new System.Windows.Forms.MenuItem();
            this.mnuCancel = new System.Windows.Forms.MenuItem();
            // 
            // lvDevices
            // 
            this.lvDevices.Columns.Add(this.clmDevice);
            this.lvDevices.HeaderStyle = System.Windows.Forms.ColumnHeaderStyle.None;
            listViewItem1.Text = "Scanning for Bluetooth devices...";
            this.lvDevices.Items.Add(listViewItem1);
            this.lvDevices.Location = new System.Drawing.Point(8, 32);
            this.lvDevices.View = System.Windows.Forms.View.Details;
            this.lvDevices.ItemActivate += new System.EventHandler(this.deviceSelected);
            // 
            // clmDevice
            // 
            this.clmDevice.Text = "ColumnHeader";
            this.clmDevice.Width = 100;
            // 
            // mainMenu1
            // 
            this.mainMenu1.MenuItems.Add(this.mnuSelect);
            this.mainMenu1.MenuItems.Add(this.mnuMenu);
            // 
            // mnuSelect
            // 
            this.mnuSelect.Enabled = false;
            this.mnuSelect.Text = "Select";
            this.mnuSelect.Click += new System.EventHandler(this.deviceSelected);
            // 
            // mnuMenu
            // 
            this.mnuMenu.Enabled = false;
            this.mnuMenu.MenuItems.Add(this.mnuAgain);
            this.mnuMenu.MenuItems.Add(this.mnuCancel);
            this.mnuMenu.Text = "Menu";
            // 
            // mnuAgain
            // 
            this.mnuAgain.Text = "Search Again";
            this.mnuAgain.Click += new System.EventHandler(this.mnuAgain_Click);
            // 
            // mnuCancel
            // 
            this.mnuCancel.Text = "Cancel";
            this.mnuCancel.Click += new System.EventHandler(this.mnuCancel_Click);
            // 
            // SelectBluetoothDeviceForm
            // 
            this.ClientSize = new System.Drawing.Size(634, 671);
            this.ControlBox = false;
            this.Controls.Add(this.lvDevices);
            this.Menu = this.mainMenu1;
            this.Text = "Bluetooth";
            this.Resize += new System.EventHandler(this.SelectBluetoothDeviceForm_Resize);
            this.Load += new System.EventHandler(this.SelectBluetoothDeviceForm_Load);

		}
		#endregion

		private void mnuCancel_Click(object sender, System.EventArgs e)
		{
			this.DialogResult = DialogResult.Cancel;
		}

		private void SelectBluetoothDeviceForm_Load(object sender, System.EventArgs e)
		{
			Cursor.Current = Cursors.WaitCursor;
			bkSearch.RunWorkerAsync();
		}

		private void SelectBluetoothDeviceForm_Resize(object sender, System.EventArgs e)
		{
#if !V1
            //do gradient view
            SendMessage(lvDevices.Handle, LVM_SETEXTENDEDLISTVIEWSTYLE, LVS_EX_GRADIENT, LVS_EX_GRADIENT);
#endif

			//set layout dynamically
			this.Bounds = new Rectangle(0,0,Screen.PrimaryScreen.WorkingArea.Width,Screen.PrimaryScreen.WorkingArea.Height);
			//fill the screen
			lvDevices.Bounds = new Rectangle(-1,-1,this.Width+2,this.Height+2);
			lvDevices.Columns[0].Width = this.Width;
		}

		private void bkSearch_DoWork(object sender, DoWorkEventArgs e)
		{
			BluetoothClient bc = new BluetoothClient();
            devices = bc.DiscoverDevices(255, fShowAuthenticated, fShowRemembered, fShowUnknown);
			bc.Dispose();
		}

        private void bkSearch_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
		{
			lvDevices.Items.Clear();

            // See if the background worker method failed
            if (devices == null) {
#if DEBUG
                MessageBox.Show("devices is null, must have been an exception!");
#endif
                System.Diagnostics.Debug.Assert(e.Error as PlatformNotSupportedException != null,
                    "When devices=null, expect PlatformNotSupportedException.");
                System.Diagnostics.Debug.Assert(e.Error.InnerException as SocketException != null,
                    "When devices=null, expect innerException SocketException.");
            }
            if (devices != null) {
                foreach (BluetoothDeviceInfo bdi in devices) {
                    ListViewItem lvi = new ListViewItem(bdi.DeviceName);
                    lvDevices.Items.Add(lvi);
                }

                if (devices.Length > 0) {
                    mnuSelect.Enabled = true;
                }
            }

			mnuMenu.Enabled = true;

			lvDevices.Focus();

			Cursor.Current = Cursors.Default;
		}

		private void deviceSelected(object sender, System.EventArgs e)
		{
			if(lvDevices.SelectedIndices.Count > 0 && lvDevices.SelectedIndices[0] > -1 && lvDevices.SelectedIndices[0] < lvDevices.Items.Count )
			{
				selectedDevice = devices[lvDevices.SelectedIndices[0]];

                if (fForceAuthentication)
                {
                    //authenticate with the selected device
                }

				this.DialogResult = DialogResult.OK;
			}
		
		}

		private void mnuAgain_Click(object sender, System.EventArgs e)
		{
			Cursor.Current = Cursors.WaitCursor;
			bkSearch.RunWorkerAsync();
		}

        public override void Refresh()
        {
            lvDevices.Items.Clear();
            fShowAuthenticated = true;
            fShowUnknown = true;
            fForceAuthentication = false;
            base.Refresh();
        }
	}
}


